<template>
  <div>
    <h3>修改留言</h3>
    <div class="view" v-if="message">
      <div class="item">
        <div class="field">主题：</div>
        <div class="value">{{ message.title }}</div>
      </div>
      <div class="item">
        <div class="field">作者：</div>
        <div class="value">{{ message.author }}</div>
      </div>
      <div class="item">
        <div class="field">日期：</div>
        <div class="value">{{ message.create_date }}</div>
      </div>
      <div class="item">
        <div class="field">内容：</div>
        <div class="value">
          <n-input type="textarea" v-model:value="message.content"/>
        </div>
      </div>
      <div class="item">
        <div class="field"></div>
        <div class="value">
          <n-button type="info" @click="modify" :loading="requesting" :disabled="requesting">修改留言</n-button>
        </div>
      </div>
    </div>
    <div v-else>
      <n-p>在左侧点击高亮的留言即可进入修改状态</n-p>
    </div>
  </div>
</template>

<script setup>

import {useRequests} from "@/common/requests.js";
import {useMessage, useNotification} from "naive-ui";
import {ref} from "vue";

const emits = defineEmits(['messageChange'])
const props = defineProps(['message'])

const requests = useRequests()
const msg = useMessage()
const notify = useNotification()

const requesting = ref(false)
const modify = () => {
  if (requesting.value) {
    return false
  }

  const data = props.message
  if (!data.content?.length) {
    msg.info("留言内容不能为空")
  }

  requesting.value = true
  requests.message.modify({id: data.id, content: data.content}).then(resp => {
    requesting.value = false
    if (resp.ret === 0) {
      emits('messageChange', data)
      msg.success("修改成功")
    } else {
      msg.error(resp?.data ?? resp?.msg ?? "未知错误")
    }
  }).catch(err => {
    requesting.value = false
    console.log(err)

    notify.error({title: '出错了', content: err.toString(), duration: 3000})
  })
}
</script>

<style lang="scss" scoped>
.view {
  .item {
    margin: .5rem 0;
    display: flex;

    .field {
      min-width: 3.25rem;
    }

    .value {
      flex: 1;
    }
  }
}
</style>
